package com.leetcode.题库;

import com.leetcode.common.model.ListNode;

/**
 * @author 覃国强
 * @date 2022-03-24 20:22
 */
public class 题库_0061_旋转链表 {


  static
  class Solution {
    public ListNode rotateRight(ListNode head, int k) {
      if (head == null || k < 1) {
        return head;
      }
      int len = length(head);

      k = k % len;
      if (k == 0) {
        return head;
      }

      ListNode tail = head;
      while (tail.next != null) {
        tail = tail.next;
      }

      k = len - k;
      ListNode node = head;
      while (k > 1) {
        node = node.next;
        --k;
      }

      tail.next = head;
      head = node.next;
      node.next = null;

      return head;
    }

    private int length(ListNode head) {
      int len = 0;
      while (head != null) {
        head = head.next;
        ++len;
      }
      return len;
    }

  }

}
